package com.sping_boot3.spirng_boot3.juc.异步回调;

import lombok.Data;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 1.1同一款产品。同时搜索出同款产品在各大电商平台的售价；
 * 1.2同一款产品。同时搜索出本产品在同一个电商平台下，各个入驻卖家售价是多少
 */
public class 各个电商平台比价案例 {
    static List<NetMall> list = Arrays.asList(
            new NetMall("拼夕夕"),
            new NetMall("淘宝"),
            new NetMall("京东"),
            new NetMall("得物"));
    public static  List<String> getPrice(List<NetMall> list, String project){
        return list
                .stream()
                .map(netMall ->
                        String.format(project + " in %s price is %.2f",
                                netMall.getName(),
                                netMall.price(project)))
                .collect(Collectors.toList());
    }
    public static  List<String> getPriceCompletableFuture(List<NetMall> list, String project){
        return list
                .stream()
                .map(netMall -> CompletableFuture.supplyAsync(() ->
                    String.format(project + " in %s price is %.2f",
                            netMall.getName(),
                            netMall.price(project))
                )).collect(Collectors.toList()).stream().map(s ->s.join()).collect(Collectors.toList());
    }
    public static void main(String[] args) {

        long startTime = System.currentTimeMillis();
        List<String> mysql = getPriceCompletableFuture(list, "mysql");
        for (String s : mysql) {
            System.out.println(s);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("花费:"+String.valueOf(endTime-startTime)+"毫秒");

    }
}
@Data
class NetMall{
    //电商平台名字，京东，淘宝
    private String name;

    public NetMall(String name) {
        this.name = name;
    }

    /**
     * 查询商品价格
     * @param projectName 商品名称
     * @return
     */
    public double price(String projectName){
        try {Thread.sleep(new Random().nextInt(500,2000));} catch (InterruptedException e) {throw new RuntimeException(e);}
        return new Random().nextDouble() * 2 + projectName.charAt(0);
    }
}
